package com.gxsyh.nantie.permission.provider.controller;

import com.gxsyh.nantie.commons.configure.rabbitmq.RabbitMQConfig;
import com.gxsyh.nantie.commons.dto.ResponseResult;
import com.gxsyh.nantie.commons.dto.SendLogResult;
import com.gxsyh.nantie.commons.utils.OkHttpClientUtil;
import com.gxsyh.nantie.permission.provider.controller.dto.CancelSubsidy;
import com.gxsyh.nantie.permission.provider.controller.dto.PersionParam;
import com.gxsyh.nantie.permission.provider.domain.TbRole;
import com.gxsyh.nantie.permission.provider.domain.TbUser;
import com.gxsyh.nantie.permission.provider.service.TbRoleService;
import com.gxsyh.nantie.permission.provider.service.TbUserRoleService;
import com.gxsyh.nantie.permission.provider.service.TbUserService;
import okhttp3.ResponseBody;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @email yom535@outlook.com
 * @author: 刘锋嘉(Liu Fengjia)
 * @date: 2020/1/14
 * @time: 17:15
 * @Description:
 */
@Transactional
@RestController
public class PermissionController {
    @Resource
    TbUserRoleService tbUserRoleService;

    @Resource
    TbUserService tbUserService;

    @Value("${base.config.leaf.url}")
    String LEAF_URL;

    @Value("${base.config.oauth.hostname}")
    String oauthHostname;

    @Value("${base.config.oauth.port}")
    String oauthPort;

    @Resource
    AmqpTemplate amqpTemplate;

    @Resource
    TbRoleService tbRoleService;

    /**
     * 设置权限
     * @param userId
     * @param persionParam
     * @param request
     * @return
     * @throws IOException
     */
    @PostMapping(value = "/permission/update/one/user/{userId}")
    public ResponseResult<Void> updatePermission(@PathVariable Long userId, @RequestBody PersionParam persionParam, HttpServletRequest request) throws IOException {

        OkHttpClientUtil.getInstance().getData("http://"+oauthHostname + ":" + oauthPort + "/users/logout?userId=" + userId).body().string();
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String name = authentication.getName();
        Long aUserId = Long.valueOf(name);
        if (aUserId.equals(userId)){
            return new ResponseResult<>(HttpStatus.INTERNAL_SERVER_ERROR.value(),"抱歉不可以设置自己的权限",null);
        }

        tbUserRoleService.deleteTbUserRoleByUserId(userId);

        List<Long> persionList=new ArrayList();
        if (persionParam.isDiningManagement())
        {
            persionList.add(4L);
        }
        if (persionParam.isUserManagement())
        {
            persionList.add(3L);
        }
        if (persionParam.isPermissionManagement())
        {
            persionList.add(6L);
        }
        if (persionParam.isRefundManagement())
        {
            persionList.add(7L);
        }
        if (persionParam.isSubsidy()){
            tbUserService.updateTbUserSubsidyStatus(userId,1);
        }
        else
        {
            tbUserService.updateTbUserSubsidyStatus(userId,0);
        }

        for (Long persionId : persionList) {
            ResponseBody body = OkHttpClientUtil.getInstance().getData(LEAF_URL + "persion").body();
            tbUserRoleService.insterTbUserRoleByUserId(Long.valueOf(body.string()),userId,persionId);
        }

        //                使用消息队列发送日志
        SendLogResult sendLogResult = new SendLogResult();
        sendLogResult.setUserId(Long.valueOf(name));
        sendLogResult.setUsername(String.valueOf(userId));
        sendLogResult.setInfo("向ID为"+userId+"设置了权限");
        amqpTemplate.convertAndSend(RabbitMQConfig.SEND_LOG_QUEUE,sendLogResult);
//                end消息队列发送日志

        return new ResponseResult<>(HttpStatus.OK.value(),"更新权限成功",null);
    }

    /**
     *查询某个用户的角色
     * 注意 为了防止要死权限管理崩了 导致整个项目进不去 我把这个查询某个用户的角色放在用户管理(nantie-user-management-provider)那个模块里面
     */
    @GetMapping(value = "/permission/get/one/user/role")
    public ResponseResult<PersionParam> getRole(@RequestParam Long userId){
        PersionParam persionParam=new PersionParam();
        List<TbRole> roleInfo = tbRoleService.getRoleInfo(userId);
        for (TbRole tbRole : roleInfo) {
            String enname = tbRole.getEnname().trim();
            if (enname.equals("diningManagement")){
                persionParam.setDiningManagement(true);
            }
            if (enname.equals("userManagement")){
                persionParam.setUserManagement(true);
            }
            if (enname.equals("permissionManagement")){
                persionParam.setPermissionManagement(true);
            }
            if (enname.equals("refundManagement")){
                persionParam.setRefundManagement(true);
            }
            if (enname.equals("superAdmin")){
                persionParam.setDiningManagement(true);
                persionParam.setUserManagement(true);
                persionParam.setPermissionManagement(true);
                persionParam.setRefundManagement(true);
            }
        }

        TbUser tbUser = tbUserService.selectOneUserById(userId);
        if (tbUser.getSubsidyStatus()==1){
            persionParam.setSubsidy(true);
        }

        return new ResponseResult<>(HttpStatus.OK.value(),"查询权限成功",persionParam);
    }

    /**
     * 批量取消餐补权限
     * @param cancelSubsidy
     * @return
     */
    @PostMapping(value = "/permission/cancel/subsidy")
    public ResponseResult<Void> cancelSubsidy(@RequestBody CancelSubsidy cancelSubsidy, HttpServletResponse response)
    {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        int change=0;
        Long[] userId = cancelSubsidy.getUserId();
        for (Long aUserId : userId) {
            if (Long.valueOf(authentication.getName()).equals(aUserId))
            {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                response.setStatus(HttpStatus.BAD_REQUEST.value());
                return new ResponseResult<>(HttpStatus.BAD_REQUEST.value(),"不可以设置自己的权限",null);
            }
            int result = tbUserService.updateTbUserSubsidyStatus(aUserId, 0);
            change=change+result;
        }
        return new ResponseResult<>(HttpStatus.OK.value(),"成功取消"+change+"人餐补",null);
    }
}
